#!/bin/zsh
# GIFFTRIPPAUDIO Arcadia Live Pack Map Tracker macOS launcher V2.31
# Changes: Runs the bundled universal read-only helper and opens the tracker UI.

set -u

APP_VERSION="V2.31"
APP_ROOT="${0:A:h:h}"
BUNDLED_NODE="$APP_ROOT/Resources/bin/node"
PROXY_FILE="$APP_ROOT/Resources/arcadia-pack-map-tracker-live-proxy.mjs"
TRACKER_PORT_NUMBER=4180
LOG_FILE="/tmp/gifftrippaudio-arcadia-pack-map-tracker-v2.31.log"

if [[ ! -x "$BUNDLED_NODE" || ! -f "$PROXY_FILE" ]]; then
  osascript -e 'display alert "Arcadia Pack Map Tracker" message "The bundled tracker runtime is incomplete." as critical' >/dev/null 2>&1 || true
  exit 1
fi

for candidate in {4180..4189}; do
  if lsof -nP -iTCP:"$candidate" -sTCP:LISTEN >/dev/null 2>&1; then
    health_json=$(curl -fsS "http://127.0.0.1:$candidate/health" 2>/dev/null || true)
    helper_version=$("$BUNDLED_NODE" -e 'try{const value=JSON.parse(process.argv[1]);process.stdout.write(value.version||"")}catch{}' "$health_json" 2>/dev/null || true)
    helper_mode=$("$BUNDLED_NODE" -e 'try{const value=JSON.parse(process.argv[1]);process.stdout.write(value.mode||"")}catch{}' "$health_json" 2>/dev/null || true)
    if [[ "$helper_version" == "$APP_VERSION" && "$helper_mode" == "read-only" ]]; then
      open "http://127.0.0.1:$candidate/"
      exit 0
    fi
    continue
  fi
  TRACKER_PORT_NUMBER=$candidate
  break
done

if lsof -nP -iTCP:"$TRACKER_PORT_NUMBER" -sTCP:LISTEN >/dev/null 2>&1; then
  osascript -e 'display alert "Arcadia Pack Map Tracker" message "Ports 4180 through 4189 are already in use." as warning' >/dev/null 2>&1 || true
  exit 1
fi

export TRACKER_PORT="$TRACKER_PORT_NUMBER"
"$BUNDLED_NODE" "$PROXY_FILE" >> "$LOG_FILE" 2>&1 &
HELPER_PID=$!

cleanup() {
  kill "$HELPER_PID" >/dev/null 2>&1 || true
}
trap cleanup EXIT INT TERM HUP

for attempt in {1..60}; do
  if curl -fsS "http://127.0.0.1:$TRACKER_PORT_NUMBER/health" >/dev/null 2>&1; then
    open "http://127.0.0.1:$TRACKER_PORT_NUMBER/"
    wait "$HELPER_PID"
    exit $?
  fi
  if ! kill -0 "$HELPER_PID" >/dev/null 2>&1; then
    break
  fi
  sleep 0.1
done

osascript -e 'display alert "Arcadia Pack Map Tracker" message "The read-only helper could not start. See /tmp/gifftrippaudio-arcadia-pack-map-tracker-v2.31.log." as critical' >/dev/null 2>&1 || true
exit 1
